package com.data.service.impl;

import com.data.config.DynamicDataSource;
import com.data.entity.Tenant;
import com.data.mapper.TenantMapper;
import com.data.service.TenantService;
import com.data.sql.SqlExecute;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ytj
 * @date 2024/4/22
 */
@Service
public class TenantServiceImpl implements TenantService {
    @Resource
    private TenantMapper tenantMapper;
    @Resource
    private DynamicDataSource dataSource;

    @Override
    public List<Tenant> selectAll() {
        return this.tenantMapper.selectAll();
    }

    @Override
    public void add(Tenant tenant) {
        try {
            this.tenantMapper.add(tenant);
            //动态创建租户库
            this.tenantMapper.createData(tenant.getCode());
            //初始化租户库基础表
            SqlExecute.execute(tenant);
            //将租户数据库信息加载到动态数据源中
            dataSource.setDataSoure(tenant);
        } catch (Exception e) {
            System.out.println("新增租户出错:"+e.getMessage());
        }
    }
}
